// src/solana.js
import { Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';
import { Metaplex, bundlrStorage } from '@metaplex/js';
import { walletAdapterIdentity } from '@metaplex/js/lib/plugins';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

const getProvider = () => {
  if (window.solana) {
    const provider = window.solana;
    if (provider.isPhantom) {
      return provider;
    }
  }
  window.open('https://phantom.app/', '_blank');
};

export const getAddressNFTs = async (walletAddress) => {
  const publicKey = new PublicKey(walletAddress);
  // Initialize Phantom Wallet Adapter
  const wallet = new PhantomWalletAdapter();
  await wallet.connect();

  const metaplex = new Metaplex(connection);
  metaplex.use(walletAdapterIdentity(wallet)).use(bundlrStorage());

  const nfts = await metaplex.nfts().findAllByOwner(publicKey);
  return nfts.map(nft => ({
    name: nft.name,
    uri: nft.metadataUri,
  }));
};

export const connectWallet = async () => {
  const provider = getProvider();
  if (provider) {
    try {
      const response = await provider.connect();
      return response.publicKey.toString();
    } catch (err) {
      console.error('Wallet connection failed', err);
    }
  }
};